package ru.spb.osll.myfit.client.widget;

import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.*;
import ru.spb.osll.myfit.client.PageMode;
import ru.spb.osll.myfit.client.log.RemoteLogger;
import ru.spb.osll.myfit.common.Content;
import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.PageElementType;
import ru.spb.osll.myfit.common.TreeNode;

import java.util.Iterator;
import java.util.List;

/**
 * Created by IntelliJ IDEA. User: Vassar Date: 09.03.2011 Time: 17:41:37 To
 * change this template use File | Settings | File Templates.
 */
public class ContentWidget extends PageElementWidget {
  private TreeNode m_treeNode;
  private PageElementType m_type;
  private final int m_level;

  public ContentWidget(GWTWidgetFactory gwtWidgetFactory, Content content) {
    super(gwtWidgetFactory);
    sinkEvents(Event.ONMOUSEUP | Event.ONDBLCLICK | Event.ONCONTEXTMENU);
    createPopupMenu();
    RemoteLogger.log(3, "i'm in ContentWidget class constructor\n");

    m_treeNode = content.getTreeNode();
    m_type = content.getType();
    m_level = content.getLevel();
    initWidget(createWidget());
    m_mode = PageMode.EDIT;
  }

  protected Widget createWidget() {
    RemoteLogger.log(3, "i'm in createContentWidget()\n");

    Tree tree = new Tree();
    RemoteLogger.log(3, "empty tree created\n");
    if (m_treeNode != null) {
      RemoteLogger.log(3, "before getTreeItem() call\n");
      tree.addItem(getTreeItem(m_treeNode));
      RemoteLogger.log(3, "after getTreeItem() call\n");
    }

    FlexTable layout = m_gwtWidgetFactory.createFlexTable();
    layout.setCellSpacing(6);
    layout.setWidget(0, 0, tree);

    DecoratorPanel panel = m_gwtWidgetFactory.createDecoratorPanel();
    panel.setWidget(layout);

    RemoteLogger.log(3, "tree is created\n");

    return panel;
  }

  private TreeItem getTreeItem(TreeNode root) {
    RemoteLogger.log(3, "node \n" + root.getReference());
    TreeItem outerRoot = new TreeItem(root.getReference());
    if (root.getChildren() != null) {
      addChildren(root.getChildren(), outerRoot);
    }

    return outerRoot;
  }

  private void addChildren(List<TreeNode> children, TreeItem root) {
    Iterator<TreeNode> iterator = children.iterator();
    while (iterator.hasNext()) {
      TreeItem item = getTreeItem(iterator.next());
      root.addItem(item);
    }
  }

  @Override
  public PageElement save() {
    return new Content(m_level);
  }

  @Override
  public void setOpen(boolean isOpen) {
    // To change body of implemented methods use File | Settings | File
    // Templates.
  }

  @Override
  public PageElementType getType() {
    return m_type;
  }
}
